import { AbortablePromise, RequestConfig } from "./types";
import { defHttp } from '@/utils/http';
/**
 * 流式请求构建器，支持链式调用
 */
export class StreamBuilder<T = any> {
  private config: RequestConfig;
  private chunkHandler?: (chunk: string) => void;
  private completeHandler?: () => void;
  private errorHandler?: (error: any) => void;
  private cancelHandler?: () => void;
  private buffer: string = '';
  private bufferMode: boolean = false;
  
  constructor(config: RequestConfig) {
    this.config = config;
  }
  
  /**
   * 设置数据块接收处理器
   */
  onChunk(handler: (chunk: string) => void): this {
    this.chunkHandler = handler;
    return this;
  }
  
  /**
   * 设置请求完成处理器
   */
  onComplete(handler: () => void): this {
    this.completeHandler = handler;
    return this;
  }
  
  /**
   * 设置错误处理器
   */
  onError(handler: (error: any) => void): this {
    this.errorHandler = handler;
    return this;
  }
  

  
  /**
   * 设置取消处理器
   */
  onCancel(handler: () => void): this {
    this.cancelHandler = handler;
    return this;
  }
  
  /**
   * 启动流式请求
   * @returns 可中止的Promise
   */
  start(): AbortablePromise<T> {
    return defHttp.stream<T>(
      this.config,
      {
        onChunkReceived: this.chunkHandler,
        onComplete: this.completeHandler,
        onError: this.errorHandler,
        onCancel: this.cancelHandler
      }
    );
  }
}

/**
 * 创建流式请求构建器
 * @param config 请求配置
 * @returns 流构建器实例
 */
export function createStreamBuilder<T = any>(config: RequestConfig): StreamBuilder<T> {
  return new StreamBuilder<T>(config);
} 